package cn.itcast.mq.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SpringRabbitListener {

//    @RabbitListener(queues = "simple.queue")
//    public void listenSimpleQueue(String msg, Channel channel, Message message) throws IOException {
//        try {
//            log.debug("消费者接收到simple.queue的消息：【" + msg + "】");
//            System.out.println(1/0);
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        } catch (Exception e) {
//            log.error("消费者消费失败了");
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
//        }
//    }

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue(String msg) {
        log.debug("消费者接收到simple.queue的消息：【" + msg + "】");
//        System.out.println(1 / 0);
        log.debug("消费者处理消息成功了");
    }

    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(name = "dl.queue", durable = "true"),
            exchange = @Exchange(name = "dl.direct"),
            key = "dl")
    )
    public void listenDlQueue(String msg) {
        log.info("接收到 dl.queue的延迟消息：{}", msg);
    }

    /**
     * 延迟消息-延迟插件
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "delay.queue",
    durable = "true"),exchange = @Exchange(name = "delay.direct",delayed = "true"),
    key = "delay"))
    public void listenDelayedQueue(String msg) {
        log.info("接收到 delay.queue的延迟消息，{}",msg);
    }


    /**
     * 普通队列
     * @param msg
     */
    @RabbitListener(queues = "normal.queue")
    public void listenNormalQueue(String msg) {
        log.debug("消费者接收到normal.queue的消息：【" + msg + "】");
    }

    /**
     * 惰性队列
     * @param msg
     */
    @RabbitListener(queuesToDeclare = @Queue(name = "lazy.queue",durable = "true",
    arguments = @Argument(name = "x-queue-mode",value = "lazy")))
    public void listenLazyQueue(String msg) {
        log.info("接收到 lazy.queue的消息:{}",msg);
    }

}
